package com.yangye.wechat.utils;

import com.yangye.wechat.constants.Constants;
import org.springframework.util.StringUtils;

import java.util.Map;

public class AccessTokenUtil {

	private static final JsonMapper jsonMapper = JsonMapper.JSON_NON_DEFAULT_MAPPER;

	private static volatile String accessToken;

	/**
	 * 添加AccessToken参数到url
	 * @param url
	 * @return
	 */
	public static String addAccessToken(String url) {
		StringBuilder requestUrl = new StringBuilder(url);
		if (requestUrl.indexOf("?") != -1){
			requestUrl.append("&access_token=").append(accessToken);
		} else {
			requestUrl.append("?access_token=").append(accessToken);
		}
		return requestUrl.toString();
	}

	/**
	 * 更新AccessToken
	 * @return
	 */
	public static String updateAccessToken() {
		StringBuilder requestUrl = new StringBuilder(Constants.GET_ACCESS_TOKEN_URL);
		requestUrl.append("&appid=").append(Constants.APPID)
				.append("&secret=").append(Constants.SECRET);
		String result = HttpClientUtil.sendHttpGet(requestUrl.toString());
		Map<String, Object> resultMap = jsonMapper.fromJson(result, Map.class);
		accessToken = String.valueOf(resultMap.get("access_token"));
		return accessToken;
	}

	public static void main(String[] args) {
		updateAccessToken();
		System.out.println(accessToken);
	}
}
